package oktx.dubbo.config;

import com.alibaba.dubbo.config.*;
import com.alibaba.dubbo.rpc.RpcContext;
import oktx.config.OktxAutoConfiguration;
import oktx.dubbo.terminator.DubboTxTerminatorService;
import oktx.terminator.TransactionTerminatorBean;
import oktx.dubbo.terminator.DubboTxTerminator;
import oktx.config.LocalTxTerminator;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

/**
 * Created by dave on 18-5-19 下午9:21.
 */
@Configuration
@ConditionalOnClass(RpcContext.class)
@AutoConfigureAfter(OktxAutoConfiguration.class)
@Import({DubboTxTerminator.class, DubboBeanPostProcessor.class})
public class DubboTxAutoConfig implements InitializingBean {
    @Autowired LocalTxTerminator terminator;
    @Autowired ApplicationConfig applicationConfig;
    @Autowired RegistryConfig registryConfig;
    @Autowired ProtocolConfig protocolConfig;
    @Autowired ConsumerConfig consumerConfig;

    @Override
    public void afterPropertiesSet() throws Exception {
        ReferenceConfig<TransactionTerminatorBean> reference = new ReferenceConfig<>();
        reference.setInterface(TransactionTerminatorBean.class);
        reference.setApplication(applicationConfig);
        reference.setConsumer(consumerConfig);
        reference.setRegistry(registryConfig);
        reference.setCheck(false);
        reference.get();

        DubboTxTerminatorService terminatorService = new DubboTxTerminatorService(terminator);
        ServiceConfig<DubboTxTerminatorService> service = new ServiceConfig<>();
        service.setInterface(TransactionTerminatorBean.class);
        service.setRef(terminatorService);
        service.setApplication(applicationConfig);
        service.setRegistry(registryConfig);
        service.setProtocol(protocolConfig);
        service.export();
    }
}
